package com.woorigil.social.parser.tmon;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class TmonHtmlParser {
	private static Logger log = LoggerFactory.getLogger(TmonHtmlParser.class);
	
	String baseUrl = "http://m.ticketmonster.co.kr/deal?cat=store&subcat=${}";
	static Map<Integer, List<String>> shoppingUrls = new HashMap<Integer, List<String>>() {{
		put(2, Arrays.asList("store_fashion_wear"));
		put(3, Arrays.asList("store_fashion_items"));
		put(4, Arrays.asList("store_beauty"));
		put(5, Arrays.asList("store_food"));
		put(6, Arrays.asList("store_sports"));
		put(7, Arrays.asList("store_electronic"));
//		put(8, Arrays.asList(""));	//가전
		put(9, Arrays.asList("store_baby"));
		put(10, Arrays.asList("store_life"));
		put(11, Arrays.asList("store_deco", "store_design"));
		put(12, Arrays.asList("store_online_mall"));
	}};
	
	public Map<String, TmonExtraDeal> parse() {
		Map<String, TmonExtraDeal> tmonExtraDeals = new HashMap<String, TmonExtraDeal>();
		for (Entry<Integer, List<String>> entry : shoppingUrls.entrySet()) {
			for (String each : entry.getValue()) {
				try {
					String url = baseUrl.replace("${}", each);
					
					log.info("TM : " + url);
					
					Document doc = Jsoup.connect(url).timeout(10000).get();
					Elements td1s = doc.select(".deal_area ul li");
					
					for (Element element : td1s) {
						TmonExtraDeal deal = new TmonExtraDeal();
						deal.setMetaId(extractMetaId(element.select("a").attr("href")));
						deal.setCategory(each);
						deal.setCategoryId(entry.getKey());
						tmonExtraDeals.put(deal.getMetaId(), deal);						
					}
				} catch (Exception e) {
					log.error(e.getMessage(), e);
				}
			}
		}
		return tmonExtraDeals;
	}

	protected String extractMetaId(String url) {
		if (StringUtils.isNotBlank(url)) {
			return url.substring(url.indexOf("/detailDaily/") + 13, url.indexOf("?"));
		}
		return null;
	}
}
